<template>
  <el-container class="Group-lessons">
    <el-header></el-header>
    <el-main>
      <div class="Group-lessons-main">
        <div class="Group-lessons-main-1">
          <div class="add-title">
            <span>{{ lessonText }}</span>
            <el-button type="primary" :icon="ArrowLeft" class="back-style"
              ><router-link to="/mainView/PrivateEducationManagement"
                >返回</router-link
              ></el-button
            >
          </div>
          <el-row class="form-add">
            <el-form
              ref="ruleFormRef"
              :model="ruleForm"
              :rules="rules"
              label-width="120px"
              class="demo-ruleForm"
              :size="formSize"
              status-icon
            >
              <el-form-item label="课程名称" prop="courseName">
                <el-input v-model="ruleForm.courseName" class="input-1-style" />
              </el-form-item>
              <el-form-item label="课程图片" prop="name">
                <el-upload
                  :limit="1"
                  action="#"
                  list-type="picture"
                  :auto-upload="false"
                  accept="image/png,image/gif,image/jpg,image/jpeg"
                  :on-change="imgSaveToUrl"
                  :show-file-list="false"
                  ref="frontUpload"
                >
                  <img
                    style="width: 100px; height: 100px"
                    v-if="imageFrontUrl"
                    :src="imageFrontUrl"
                  />
                  <el-button>上传图片</el-button>
                </el-upload>
                <span class="span-color"
                  >(建议正方形图片,大小不超过2M。支持格式jpg、jpeg、gif、png)</span
                >
              </el-form-item>
              <el-form-item label="课程视频地址" prop="videoUrl">
                <el-input
                  v-model="ruleForm.videoUrl"
                  class="input-1-style"
                  placeholder="仅支持腾讯视频"
                />
              </el-form-item>
              <el-form-item label="课程时长" prop="courseDuration">
                <el-input
                  v-model="ruleForm.courseDuration"
                  suffix-icon="currency"
                  class="input-1-style"
                  ><template #append>分钟</template></el-input
                >
              </el-form-item>
              <el-form-item label="每日课时上限" prop="courseHouseRestrict">
                <el-input
                  v-model="ruleForm.courseHouseRestrict"
                  suffix-icon="currency"
                  class="input-1-style"
                  ><template #append>人</template></el-input
                >
              </el-form-item>
              <el-form-item label="教练" prop="courseCoachId">
                <el-select
                  v-model="ruleForm.courseCoachId"
                  class="m-2"
                  placeholder="请选择课程教练"
                >
                  <el-option
                    v-for="item in coach.coachList"
                    :key="item.name"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="课时费" prop="courseFee">
                <div class="courseFee">
                  <el-input
                    v-model="obj1.courseFee"
                    suffix-icon="currency"
                    class="input-1-style"
                    ><template #append>课时</template></el-input
                  >
                  <el-input
                    v-model="obj1.courseHourse"
                    suffix-icon="currency"
                    class="input-1-style wx333"
                    ><template #append>元</template></el-input
                  >
                </div>
                <div>
                  <span>是否体验</span>
                  <el-radio-group v-model="obj1.isTrial">
                    <el-radio label="是" />
                    <el-radio label="否" />
                  </el-radio-group>
                </div>
              </el-form-item>
              <el-form-item label="课程备注" prop="remark">
                <el-input
                  v-model="ruleForm.remark"
                  suffix-icon="currency"
                  class="input-1-style"
                />
              </el-form-item>
              <el-form-item label="课程标签" required>
                <el-tag
                  v-for="tag in dynamicTags"
                  :key="tag"
                  class="mx-1"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(tag)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  v-if="inputVisible"
                  ref="InputRef"
                  v-model="inputValue"
                  class="ml-1 w-20"
                  size="small"
                  @keyup.enter="handleInputConfirm"
                  @blur="handleInputConfirm"
                />
                <el-button
                  v-else
                  class="button-new-tag ml-1"
                  size="small"
                  @click="showInput"
                >
                  + 添加
                </el-button>
              </el-form-item>
              <el-form-item label="课程介绍" prop="description">
                <el-input
                  v-model="ruleForm.description"
                  :rows="2"
                  type="textarea"
                  placeholder="Please input"
                />
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  @click="submitForm(ruleFormRef)"
                  :plain="true"
                  >确定</el-button
                >
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
              </el-form-item>
            </el-form>
          </el-row>
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<script lang="ts" setup>
import { ArrowLeft } from "@element-plus/icons-vue";
import { reactive, ref, nextTick, toRefs, onMounted } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElInput } from "element-plus";
import { Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue";
import {
  addPrivateCourse,
  findClassList,
  updatePrivateCourse,
  findIdPrivateCourse,
  findCoach,
  uploadImage,
} from "../../http/api";
import router from "../../router";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";

import type { UploadFile } from "element-plus";
const flag = useRoute().query.flag;
// 标题
let lessonText = ref("");
// 编辑时路由传过来的id
let zid = useRoute().query.zid;
const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
  id: null,
  imgs: [],
  courseFee: [
    {
      courseFee: "",
      courseHourse: "",
      isTrial: "",
      privateCourseId: 1,
    },
  ],
  courseTag: "",
  courseName: "魔鬼速度减脂课程",
  videoUrl: "",
  courseDuration: "",
  courseHouseRestrict: "",
  courseCoachId: "",
  remark: "",
  description:
    "根据不同年龄段，儿童身体和心理特征，通过故事及游戏的方式，打造的一套以趣味运动为主的训练计划",
});
let obj1 = reactive(ruleForm.courseFee[0]);
const rules = reactive<FormRules>({
  courseName: [{ required: true, message: "请输入课程名称", trigger: "blur" }],
  videoUrl: [
    { required: true, message: "请输入课程视频地址", trigger: "blur" },
  ],
  courseDuration: [
    { required: true, message: "请输入课程时长", trigger: "blur" },
  ],
  courseHouseRestrict: [
    { required: true, message: "请输入每日课时上限", trigger: "blur" },
  ],
  description: [{ required: true, message: "请输入课程介绍", trigger: "blur" }],
  courseCoachId: [
    {
      required: true,
      message: "请选择教练",
      trigger: "change",
    },
  ],
});

// 标签
const inputValue = ref("");
const dynamicTags = ref([]);
const inputVisible = ref(false);
const InputRef = ref<InstanceType<typeof ElInput>>();
const handleClose = (tag: string) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1);
};

const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};

const handleInputConfirm = () => {
  if (inputValue.value) {
    dynamicTags.value.push(inputValue.value);
  }
  inputVisible.value = false;
  inputValue.value = "";
};
// 图片上传
let formData = new FormData();
const imageFrontUrl = ref("");
var imageUrl = ref("");
function imgSaveToUrl(file: any) {
  console.log(file.raw);
  formData.append("file", file.raw);
  imageFrontUrl.value = URL.createObjectURL(file.raw);
  const fileSize = file.size;
  const fileType = file.raw.type;
  if (!fileSize) {
    // 是否为空
    ElMessage({
      type: "error",
      showClose: true,
      message: "无效的文件，请重新选择！",
    });
    logoPicRemove();
    return;
  }
  if (fileSize / 1024 / 1024 > 10) {
    // 图片大小
    ElMessage({
      type: "error",
      showClose: true,
      message: "请上传小于10M的图片!",
    });
    logoPicRemove();
    return;
  }
  if (fileType.indexOf("image") === -1) {
    // 如果不是图片格式
    ElMessage({
      type: "error",
      showClose: true,
      message: "不是有效的图片文件，或格式不支持，请重新选择!",
    });
    logoPicRemove();
    return;
  }
  imageUpload();
}
function logoPicRemove() {
  // 清空内容
  imageFrontUrl.value = "";
}

async function imageUpload() {
  await uploadImage(formData).then((res: any) => {
    ruleForm.imgs.push(String(res.data));
  });
}
// 表单提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      let tagArr = [];
      toRefs(dynamicTags.value).forEach((el, index) => {
        tagArr.push(el.value);
      });
      ruleForm.courseTag = tagArr.join();
      if (obj1.isTrial == "是") {
        obj1.isTrial = "1";
      } else {
        obj1.isTrial = "0";
      }
      console.log(ruleForm);
      // 添加
      if (flag == "1") {
        addPrivateCourse(ruleForm).then((res: any) => {
          if (res.code == 0) {
            ElMessage({
              message: "添加成功！.",
              type: "success",
            });
            router.push({
              path: "/mainView/PrivateEducationManagement",
            });
          } else {
            alert(res.msg);
          }
        });
        // 编辑
      } else if (flag == "2") {
        ruleForm.id = zid;
        updatePrivateCourse(ruleForm).then((res: any) => {
          if (res.code == 0) {
            ElMessage({
              message: "编辑成功！.",
              type: "success",
            });
            router.push({
              path: "/mainView/PrivateEducationManagement",
            });
          }
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}));
// 教练列表
var coach = reactive({ coachList: [] });
// 挂在时判断是编辑还是添加
onMounted(() => {
  findCoach().then((res: any) => {
    console.log(res);
    if (res.code == 0) {
      coach.coachList = res.data;
    }
  });
  if (flag == "1") {
    lessonText.value = "私教添加";
  } else if (flag == "2") {
    lessonText.value = "私教编辑";
    findIdPrivateCourse({ id: zid }).then((res: any) => {
      imageFrontUrl.value = res.data.defaultImgUrl;
      ruleForm.imgs.push(res.data.defaultImgUrl);
      dynamicTags.value = res.data.courseTag.split(",");
      ruleForm.videoUrl = res.data.videoUrl;
      ruleForm.courseName = res.data.courseName;
      ruleForm.courseDuration = res.data.courseDuration;
      ruleForm.courseHouseRestrict = res.data.courseHouseRestrict;
      ruleForm.courseCoachId = res.data.courseCoachId;
      ruleForm.remark = res.data.remark;
      ruleForm.description = res.data.description;
    });
  }
});
</script>

<style scoped>
.Group-lessons {
  background-color: #f2f2f2;
  height: 100vh;
}
.Group-lessons-main {
  background-color: #ffffff;
  border-radius: 10px;
  padding: 10px;
}
.Group-lessons-main-1 {
  border-radius: 15px;
  border: 1px solid #e4e4e4;
  overflow: hidden;
}
.add-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f3f3f3;
  padding: 5px 10px;
}
.form-add {
  padding: 20px 100px;
}
.currency::before {
  content: "元";
}
.el-popper.is-customized {
  /* Set padding to ensure the height is 32px */
  padding: 6px 12px;
  background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
}

.el-popper.is-customized .el-popper__arrow::before {
  background: linear-gradient(45deg, #b2e68d, #bce689);
  right: 0;
}
.el-tag {
  margin-left: 10px !important;
}
.button-new-tag {
  margin-left: 10px !important;
}
.span-color {
  color: #949292;
}
/* 输入框高度 */
.input-1-style {
  height: 44px !important;
}
.back-style a {
  text-decoration: none;
  color: white;
}
.courseFee > .el-input {
  width: 222px !important;
}
.wx333 {
  margin-left: 10px;
}
</style>
